<?php





namespace app\shop\model;



use app\crm\model\FollowRecord;

use app\admin\model\Common;

use Kingdee\Kingdee;

use think\facade\Db;

use think\model\concern\SoftDelete;

use app\common\traits\ActionRecordTrait;

use app\shop\model\Refund;

use app\shop\model\AddOrderLog;

class TurnRefund extends Common

{
    use ActionRecordTrait;

    /**

     * 表名

     * @var string

     */

    protected $name = 'shop_refund_order';

    protected $defaultSoftDelete = 0;

    /**

     * 获取sku信息

     * @return \think\model\relation\hasOne

     * @author SL

     * @create 2021-05-27 15:04

     */

    public function orderGoods()

    {

        return $this->hasOne(Goods::class,'id');

    }

    public function addTurnRefund($request)
    {
        
        $refundModel = new Refund();

        $refundID = $request['refundID'] ?? '';
        $turnMoney = $request['turnMoney'] ?? 0;

        $resArr = Db::name('shop_refund_order_turn')->where([['main_refund_order_no','=',$refundID],['status','<>',2]])->select()->toArray();
        if($resArr){
            $this->error = '该订单当前有未完成的分配业绩，请勿重复提交！';
            return false;
        }

        if(!empty($refundID) && $turnMoney > 0){
            
            $refundInfo = Db::name('shop_refund_order')->where('refund_order_no',$refundID)->find();

            $refundGoodsInfo = Db::name('shop_refund_order_goods')->where('order_id',$refundInfo['id'])->find();

            $customerTel = Db::name('customer')->where('id',$refundInfo['uid'])->value('telephone');

            $referral_shop_id = $refundInfo['referral_shop_id'] ?? 0;

            $shop_info = Db::name('shop')->where('shop_id',$referral_shop_id)->find();

            // echo "<pre>";
            // print_r($shop_info);
            // echo "</pre>";

            $customer_shop_info = Db::name('customer')->where([['telephone','=',$customerTel],['shop_id','=',$referral_shop_id]])->find();

            $time = time();
            $refund_order_no = $refundModel->getOrderNo();
            $data = [
                'uid'                     => trim($customer_shop_info['id']), // 客户
                'consignee'               => trim($customer_shop_info['customer_name']), // 收货人
                'refund_order_no'         => $refund_order_no, // 订单号
                'shop_id'                 => $refundInfo['referral_shop_id'], // 门店id
                'shop_name'               => trim($refundInfo['referral_shop_name']), // 门店名称
                'referral_shop_id'        => 0, // 转诊门店id
                'referral_shop_name'      => '', // 转诊门店名称
                'coefficient'             => 1, // 统计数据计算系数
                'shop_type'               => 2, // 门店属性(2-门店)
                'create_time'             => $time, // 创建时间
                'deal_time'               => $time, // 成交日期
                'goods_price'             => 0, // 订单标准金额
                'total_amount'            => isset($request['turnMoney']) ? $request['turnMoney'] : 0, // 实退金额
                'gift_amount'             => 0, // 实退赠金
                'pay_amount'              => isset($request['turnMoney']) ? $request['turnMoney'] : 0, // 实退本金
                'description'             => '转诊业绩', // 订单描述
                'refund_type'             => '101.02', // 退款类型 101.01 店转  101.02 退款
                'status'                  => 0,
                'type'                    => 3,//退款单类型 1退款单 2退货单
                'market_id'               => isset($shop_info['market_id']) ? $shop_info['market_id'] : 0, // 市场id
                'market_name'             => isset($shop_info['market_name']) ? $shop_info['market_name'] : 0, // 市场名称
                'sales_organization'      => isset($shop_info['market_kingdee_code']) ? $shop_info['market_kingdee_code'] : 0, // 销售组织编码
                'sales_name'              => isset($shop_info['market_name']) ? $shop_info['market_name'] : '', // 销售组织名称
                'settlement_organization' => isset($shop_info['market_kingdee_code']) ? $shop_info['market_kingdee_code'] : 0, // 结算组织编码
                'settlement_name'         => isset($shop_info['market_name']) ? $shop_info['market_name'] : '', // 结算组织名称
                'is_experience'           => '', // 是否体验 0否 1是
                'experience_id'           => 0, // 体验人id
                'experience_name'         => '', // 体验人姓名
                'is_outreach'             => '', // 是否外联 0否 1是
                'outreahc_id'             => 0, // 外联人id
                'outreahc_name'           => '', // 外联人姓名
                'is_introduction'         => '', // 是否转介绍 0否 1是
                'introduction_id'         => 0, // 转介绍人id
                'introduction_name'       => '', // 转介绍人姓名
                'sale_id'                 => 0, // 销售员id
                'sale_name'               => '', // 销售员姓名
                'delivery_name'           => '', // 库存部门名称
                'delivery_king'           => '', // 库存部门编码
                'combo'                   => 0, // 退款审批类型 0没选   1项目退款 2疤痕退款
                'refund_type_plus'        => '3', // 收款方式2
                'shanghu_type'            => '', // 商户分类1是公户，2是私户
                'is_pay'                  => 1, // 是否支付：0未支付，1已支付
            ];

            $order = $this->create($data);

            if ($order) {

                $orderGoodsList = [];
                $orderGoodsList['order_id'] = $order->id;
                $orderGoodsList['create_time'] = $time;
                $orderGoodsList['refund_mode'] = $refundGoodsInfo['refund_mode'];
                $orderGoodsList['refund_mode_name'] = isset($refundGoodsInfo['refund_mode_name'])?$refundGoodsInfo['refund_mode_name']:"";
                $orderGoodsList['bank_number'] = isset($refundGoodsInfo['bank_number'])?$refundGoodsInfo['bank_number']:"";
                $orderGoodsList['data_business_type'] = isset($refundGoodsInfo['data_business_type'])?$refundGoodsInfo['data_business_type']:"";
                $orderGoodsList['data_sales_policy'] =isset($refundGoodsInfo['data_sales_policy'])?$refundGoodsInfo['data_sales_policy']:"";
                $orderGoodsList['pay_price'] = isset($request['turnMoney']) ? $request['turnMoney'] : 0;
                $orderGoodsList['gift_price'] = $refundGoodsInfo['gift_price'] ?? 0;
                $orderGoodsList['descs'] = $refundGoodsInfo['descs'];

                // refund_order_goods
                $refundGoodID = Db::name('shop_refund_order_goods')->insertGetId($orderGoodsList);

                $refund_order_turn_data = [];

                $refund_order_turn_data['main_refund_order_no'] = $refundID;
                $refund_order_turn_data['vice_refund_order_no'] = $refund_order_no;
                $refund_order_turn_data['status'] = 0;
                $refund_order_turn_data['create_time'] = $time;

                // shop_refund_order_turn
                $turnID = Db::name('shop_refund_order_turn')->insertGetId($refund_order_turn_data);
                
                $this->error = '创建成功';
                return true;
            }else{
                $this->error = '创建失败';
                return false;
            }

            

        }else{

            $this->error = '创建失败';
            return false;
        }

        // exit;
    }

    public function turnPerformanceList($request)
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;
        $where = [];

        array_push($where,['st.status','<>',2]);

        array_push($where,['so.is_pay','=',1]);

        if($request['shopIds']){
            array_push($where,['so.referral_shop_id','in',$request['shopIds']]);
        }
        

        $field = ['so.id','so.consignee', 'so.order_type','so.is_lock','so.business_type','so.shop_name','so.create_time','so.shop_id','so.deal_time','so.type','so.type','so.sale_name','c.king_no','g.refund_mode_name','g.pay_price','g.gift_price','so.refund_type','so.refund_type_plus','so.is_pay','so.is_pay_time','so.status','so.extra_type'];


        $turnPerformanceList = Db::name('shop_refund_order_turn')->alias('st')
        ->join('shop_refund_order so','st.vice_refund_order_no = so.refund_order_no')
        ->join('customer c', 'so.uid = c.id')
        ->join('shop_refund_order_goods g', 'so.id = g.order_id')
        ->where($where)->field($field)->select()->toArray();

        return [
            'dataCount' => count($turnPerformanceList),
            'list' => $turnPerformanceList,
        ];
        
    }

    public function deleteTurn($turnType,$refund_order_no)
    {
        switch($turnType)
        {
            case 'main':
                // echo "作废主单";
                $turnRefundInfo = Db::name('shop_refund_order_turn')->where([['main_refund_order_no','=',$refund_order_no],['status','<>',2]])->find();

                Db::name('shop_refund_order_turn')->where('id',$turnRefundInfo['id'])->update(['status' => 2]); // 作废关联表
                Db::name('shop_refund_order')->where('refund_order_no',$turnRefundInfo['vice_refund_order_no'])->update(['status' => 3]); // 作废从单主表
                break;
            case 'vice':
                // echo "作废从单";

                Db::name('shop_refund_order')->where('refund_order_no',$refund_order_no)->update(['status' => 3]); // 作废从单主表
                Db::name('shop_refund_order_turn')->where('vice_refund_order_no',$refund_order_no)->update(['status' => 2]); // 作废关联表
                break;
        }
    }
    
}